# _*_ coding:utf-8 _*_
# @Time  : 2023.03.30
# @Author: zizlee
import hashlib
from fastapi import APIRouter, Body
from pydantic import BaseModel, validator
from v1_all_api.all_response import AllResponse
from v1_all_api.all_utils import datetime_utils
from db import FAConnection

short_message_api = APIRouter()


class ShortMessageItem(BaseModel):
    create_time: str
    author_id: int
    content: str

    @validator('create_time')
    def validate_create_time(cls, value):
        if not datetime_utils.auth_datetime_string(value, f='%Y-%m-%d %H:%M:%S'):
            raise ValueError('create_time格式错误，接受YYYY-MM-DD HH:MM:SS')
        return value


# 上传添加一条短讯数据
@short_message_api.post('/upload/')
def save_short_message(msg: ShortMessageItem = Body(...)):
    message_md5 = hashlib.md5(msg.content.encode('utf8')).hexdigest()
    with FAConnection() as cursor:
        cursor.execute("SELECT id,md5 FROM info_short_message WHERE md5=%s;", (message_md5, ))
        is_exist = cursor.fetchone()
        if is_exist:
            return AllResponse.no_do_anything(msg='该数据已存在，无需重复保存!')
        cursor.execute("INSERT INTO info_short_message (create_time,creator,content,md5) VALUES (%s,%s,%s,%s);",
                       (msg.create_time, msg.author_id, msg.content, message_md5))
    return AllResponse.operate_successfully(msg='保存短讯数据完成。')
